/**
 * 递归获取路由及其所有子路由的权限
 * @param {Object} route - 路由对象
 * @returns {Array} - 权限数组
 */
export function getAllRoutePermissions(route) {
    const permissions = new Set()

    // 获取当前路由的权限
    if (route.meta?.permission) {
        route.meta.permission.forEach(perm => permissions.add(perm))
    }

    // 递归获取子路由的权限
    if (route.children) {
        route.children.forEach(child => {
            getAllRoutePermissions(child).forEach(perm => permissions.add(perm))
        })
    }

    return Array.from(permissions)
}

/**
 * 处理路由配置，为父路由添加子路由的权限
 * @param {Array} routes - 路由配置数组
 * @returns {Array} - 处理后的路由配置
 */
export function processRoutePermissions(routes) {
    return routes.map(route => {
        // 创建新的路由对象，避免修改原对象
        const newRoute = { ...route }

        // 如果有子路由，递归处理
        if (newRoute.children) {
            newRoute.children = processRoutePermissions(newRoute.children)

            // 如果父路由没有权限配置，则使用子路由的权限
            if (!newRoute.meta?.permission) {
                newRoute.meta = {
                    ...newRoute.meta,
                    permission: getAllRoutePermissions(newRoute)
                }
            }
        }

        return newRoute
    })
} 